package com.price.sample.http.interceptor

import com.price.common.extend.logDebug
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

class MockInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {

        val responseBuilder: Response.Builder = Response.Builder()
            .code(200)
            .message("ok")
            .request(chain.request())
            .protocol(Protocol.HTTP_1_0)
            .addHeader("content-type", "application/json")
        val request = chain.request()
        val newResponse = if (request.url.toString().contains("/test")) { //拦截指定地址
            logDebug("MockInterceptor拦截", null)
            val responseString =
                "{\"errorCode\":0,\"data\":{\"name\":\"test\",\"statu\":\"success\"},\"msg\":\"success\"}"
            responseBuilder.body(
                responseString.toByteArray().toResponseBody("application/json".toMediaTypeOrNull())
            ) //将数据设置到body中
            responseBuilder
                .build() //builder模式构建response
        }else {
            chain.proceed(request)
        }

        return newResponse
    }
}